/**
 * Created by tdzl2003 on 7/22/16.
 */

import { AsyncStorage } from 'react-native';

export default function storageCache(fetchData, options = {}) {
  const expires = options.expires || 60000;
  const storagePrefix = options.storagePrefix || 'cache-';

  return async id => {
    const cacheKey = storagePrefix + id;
    const { expireAt, data } = await AsyncStorage.getItem(cacheKey);
    if (Date.now() < expireAt) {
      return data;
    }
    const newData = await fetchData(id);
    await AsyncStorage.setItem(cacheKey, {
      expireAt: Date.now() + expires,
      data: newData,
    });
    return newData;
  };
}
